import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { tap, map } from 'rxjs/operators';
import {
    SimpleTableComponent,
    SimpleTableColumn,
    SimpleTableData,
} from '@delon/abc';
import { FormGroup, Validators, FormBuilder } from '../../../../../node_modules/@angular/forms';
import { SwiperService } from '../swiper.service';

@Component({
    selector: 'pro-table-list',
    templateUrl: 'table.component.html',
})
export class TableComponent implements OnInit {
    q: any = {
        pi: 1,
        ps: 10,
        sorter: '',
        status: null,
        statusList: [],
    };
    data: any[] = [];
    loading = false;
    status = [
        { index: 0, text: '关闭', value: false, type: 'default', checked: false },
        {
            index: 1,
            text: '运行中',
            value: false,
            type: 'processing',
            checked: false,
        },
        { index: 2, text: '已上线', value: false, type: 'success', checked: false },
        { index: 3, text: '异常', value: false, type: 'error', checked: false },
    ];

    @ViewChild('st') st: SimpleTableComponent;
    @ViewChild('modalContent') modalContent: TemplateRef<{}>;

    columns: SimpleTableColumn[] = [
        { title: '', index: 'key', type: 'checkbox' },
        { title: '图片', index: 'imageUrl', type: 'img' },
        { title: '路由', index: 'routeUrl' },
        {
            title: '显示顺序',
            index: 'sequence'
        },
        {
            title: '操作',
            buttons: [
                {
                    text: '编辑',
                    click: (item: any) => this.edit(this.modalContent, item),
                },
                {
                    text: '删除',
                    click: (item: any) => this.delete(item),
                },
            ],
        },
    ];

    selectedRows: SimpleTableData[] = [];
    description = '';
    totalCallNo = 0;
    expandForm = false;

    form: FormGroup;
    _employee: any;
    fromList: any;
    statusList: any;

    constructor(
        private http: _HttpClient,
        public msg: NzMessageService,
        private modalSrv: NzModalService,
        private fb: FormBuilder,
        private swiperService: SwiperService
    ) { }

    ngOnInit() {
        this.form = this.fb.group({
            imageUrl: [null, [Validators.required]],
            routeUrl: [null, [Validators.required]],
            sequence: [null, [Validators.required]],
        });

        this.getData();

        let temp: any = localStorage.getItem("employee");
        this._employee = JSON.parse(temp);

        this.swiperService.getValueListByParentCode("from").subscribe(resp => {
            if (resp.success)
                this.fromList = resp.data;
        })

        this.swiperService.getValueListByParentCode("customerStatus").subscribe(resp => {
            if (resp.success)
                this.statusList = resp.data;
        })

    }

    getData() {
        this.loading = true;
        this.q.statusList = this.status
            .filter(w => w.checked)
            .map(item => item.index);
        if (this.q.status !== null && this.q.status > -1)
            this.q.statusList.push(this.q.status);

        this.swiperService.query(this.q).subscribe(resp => {
            this.loading = false;
            if (resp.success)
                this.data = resp.data;
            else
                this.data = [];

        }, error => {
            this.loading = false;
            this.msg.error("error: " + JSON.stringify(error));

        });

    }

    checkboxChange(list: SimpleTableData[]) {
        this.selectedRows = list;
        this.totalCallNo = this.selectedRows.reduce(
            (total, cv) => total + cv.callNo,
            0,
        );
    }

    remove() {
        this.http
            .delete('/rule', { nos: this.selectedRows.map(i => i.no).join(',') })
            .subscribe(() => {
                this.getData();
                this.st.clearCheck();
            });
    }

    add(tpl: TemplateRef<{}>) {
        this.form.reset();

        this.modalSrv.create({
            nzWidth: 640,
            nzMaskClosable: false,
            nzTitle: '新建',
            nzContent: tpl,
            nzOkText: "提交",
            nzOnOk: () => {
                for (const i in this.form.controls) {
                    this.form.controls[i].markAsDirty();
                    this.form.controls[i].updateValueAndValidity();
                }
                if (this.form.invalid) return false;

                this.loading = true;
                this.swiperService.create(this.form.value, this._employee.id).subscribe(resp => {
                    this.loading = false;
                    if (resp.success) {
                        this.msg.success("操作成功");
                        this.getData();
                    }
                    else
                        this.msg.error(resp.errorMsg);

                }, error => {
                    this.loading = false;
                    this.msg.error("异常: " + JSON.stringify(error));

                });

                return false;
            },
            nzCancelText: null
        });
    }

    reset(ls: any[]) {
        for (const item of ls) item.value = false;
        this.getData();
    }

    edit(tpl: TemplateRef<{}>, item: any) {
        this.form.reset();
        this.form.patchValue({
            imageUrl: item.imageUrl,
            routeUrl: item.routeUrl,
            sequence: item.sequence,
        });

        this.modalSrv.create({
            nzWidth: 640,
            nzMaskClosable: false,
            nzTitle: '编辑',
            nzContent: tpl,
            nzOkText: "保存",
            nzOnOk: () => {
                for (const i in this.form.controls) {
                    this.form.controls[i].markAsDirty();
                    this.form.controls[i].updateValueAndValidity();
                }
                if (this.form.invalid) return false;

                item.imageUrl = this.form.value.imageUrl;
                item.routeUrl = this.form.value.routeUrl;
                item.sequence = this.form.value.sequence;

                this.loading = true;
                this.swiperService.edit(item).subscribe(resp => {
                    this.loading = false;
                    if (resp.success) {
                        this.msg.success("操作成功");
                        this.getData();
                    }
                    else
                        this.msg.error(resp.errorMsg);

                }, error => {
                    this.loading = false;
                    this.msg.error("异常: " + JSON.stringify(error));

                });

                return false;
            },
            nzCancelText: null
        });
    }

    delete(item: any): any {
        this.modalSrv.confirm({
            nzTitle: '确认删除么?',
            nzContent: '点击确认，继续删除。点击取消，退出操作！',
            nzOkText: "确定",
            nzCancelText: "取消",
            nzOnOk: () => {
                this.swiperService.del(item.id).subscribe(resp => {
                    if (resp.success) {
                        this.msg.success("操作成功");
                        this.getData();
                    }
                    else
                        this.msg.error(resp.errorMsg);
                }, error => {
                    this.msg.error("异常: " + JSON.stringify(error));
                });
            }
        });

    }

    export(tpl: TemplateRef<{}>) {
        this.modalSrv.create({
            // nzWidth: 320,
            nzMaskClosable: false,
            nzTitle: '导入',
            nzContent: tpl,
            nzOkText: "提交",
            nzOnOk: () => {

                return false;
            },
            nzCancelText: null
        });
    }

}
